import { defineStore } from 'pinia'
import type { 
  ConfigListItem, 
  EquipmentTemplate, 
  SkillConfig, 
  ValidationResult,
  EditorState,
  ConfigStats,
  SearchCriteria,
  SortOptions
} from '@/types/config'
import { configApi } from '@/api/config'

export const useConfigStore = defineStore('config', {
  state: () => ({
    // 配置列表
    configList: [] as ConfigListItem[],
    
    // 当前编辑的配置
    currentEquipments: [] as EquipmentTemplate[],
    currentSkills: [] as SkillConfig[],
    
    // 编辑器状态
    editorState: {
      isLoading: false,
      isDirty: false,
      lastSaved: undefined,
      autoSave: true,
      validationEnabled: true
    } as EditorState,
    
    // 验证结果
    validationResults: {} as Record<string, ValidationResult>,
    
    // 统计信息
    stats: null as ConfigStats | null,
    
    // 搜索和过滤
    searchCriteria: {} as SearchCriteria,
    sortOptions: {
      field: 'name',
      direction: 'asc'
    } as SortOptions,
    
    // 选中的配置项
    selectedConfigs: new Set<string>(),
    
    // 系统状态
    serverConnected: false,
    lastSync: 0
  }),

  getters: {
    // 获取过滤后的装备列表
    filteredEquipments: (state) => {
      let equipments = state.currentEquipments
      
      // 应用搜索条件
      if (state.searchCriteria.keyword) {
        const keyword = state.searchCriteria.keyword.toLowerCase()
        equipments = equipments.filter(eq => 
          eq.name.toLowerCase().includes(keyword) ||
          eq.id.toLowerCase().includes(keyword) ||
          (eq.description && eq.description.toLowerCase().includes(keyword))
        )
      }
      
      if (state.searchCriteria.type) {
        equipments = equipments.filter(eq => eq.type === state.searchCriteria.type)
      }
      
      if (state.searchCriteria.category) {
        equipments = equipments.filter(eq => eq.job === state.searchCriteria.category)
      }
      
      if (state.searchCriteria.enabled !== undefined) {
        equipments = equipments.filter(eq => eq.enabled === state.searchCriteria.enabled)
      }
      
      // 应用排序
      equipments.sort((a, b) => {
        const field = state.sortOptions.field as keyof EquipmentTemplate
        const aValue = a[field]
        const bValue = b[field]
        const direction = state.sortOptions.direction === 'asc' ? 1 : -1
        
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          return aValue.localeCompare(bValue) * direction
        }
        
        if (typeof aValue === 'number' && typeof bValue === 'number') {
          return (aValue - bValue) * direction
        }
        
        return 0
      })
      
      return equipments
    },

    // 获取过滤后的技能列表
    filteredSkills: (state) => {
      let skills = state.currentSkills
      
      // 应用搜索条件
      if (state.searchCriteria.keyword) {
        const keyword = state.searchCriteria.keyword.toLowerCase()
        skills = skills.filter(skill => 
          (skill.name && skill.name.toLowerCase().includes(keyword)) ||
          skill.skillId.toLowerCase().includes(keyword) ||
          (skill.description && skill.description.toLowerCase().includes(keyword))
        )
      }
      
      if (state.searchCriteria.type) {
        skills = skills.filter(skill => skill.type === state.searchCriteria.type)
      }
      
      if (state.searchCriteria.category) {
        skills = skills.filter(skill => 
          skill.category === state.searchCriteria.category ||
          skill.classType === state.searchCriteria.category
        )
      }
      
      if (state.searchCriteria.quality !== undefined) {
        skills = skills.filter(skill => skill.quality === state.searchCriteria.quality)
      }
      
      if (state.searchCriteria.level) {
        const { min, max } = state.searchCriteria.level
        skills = skills.filter(skill => {
          const level = skill.level || 1
          return (!min || level >= min) && (!max || level <= max)
        })
      }
      
      return skills
    },

    // 获取配置健康状态
    configHealth: (state) => {
      const errorCount = Object.values(state.validationResults)
        .reduce((sum, result) => sum + result.errors.length, 0)
      
      if (errorCount === 0) return 'healthy'
      if (errorCount < 5) return 'warning'
      return 'error'
    },

    // 获取需要保存的状态
    needsSaving: (state) => state.editorState.isDirty,

    // 获取已选择的配置数量
    selectedCount: (state) => state.selectedConfigs.size
  },

  actions: {
    // === 配置列表管理 ===
    async loadConfigList() {
      this.editorState.isLoading = true
      try {
        const response = await configApi.getConfigList()
        if (response.success && response.data) {
          this.configList = response.data
        }
      } catch (error) {
        console.error('Failed to load config list:', error)
      } finally {
        this.editorState.isLoading = false
      }
    },

    // === 装备配置管理 ===
    async loadEquipments() {
      this.editorState.isLoading = true
      try {
        const response = await configApi.getEquipments()
        if (response.success && response.data) {
          this.currentEquipments = response.data
          this.editorState.isDirty = false
        }
      } catch (error) {
        console.error('Failed to load equipments:', error)
      } finally {
        this.editorState.isLoading = false
      }
    },

    async saveEquipments() {
      this.editorState.isLoading = true
      try {
        const response = await configApi.saveEquipments(this.currentEquipments)
        if (response.success) {
          this.editorState.isDirty = false
          this.editorState.lastSaved = Date.now()
          return true
        }
        return false
      } catch (error) {
        console.error('Failed to save equipments:', error)
        return false
      } finally {
        this.editorState.isLoading = false
      }
    },

    addEquipment(equipment: EquipmentTemplate) {
      this.currentEquipments.push(equipment)
      this.markDirty()
    },

    updateEquipment(id: string, equipment: Partial<EquipmentTemplate>) {
      const index = this.currentEquipments.findIndex(eq => eq.id === id)
      if (index !== -1) {
        this.currentEquipments[index] = { ...this.currentEquipments[index], ...equipment }
        this.markDirty()
      }
    },

    removeEquipment(id: string) {
      const index = this.currentEquipments.findIndex(eq => eq.id === id)
      if (index !== -1) {
        this.currentEquipments.splice(index, 1)
        this.markDirty()
      }
    },

    // === 技能配置管理 ===
    async loadSkills() {
      this.editorState.isLoading = true
      try {
        const response = await configApi.getSkills()
        if (response.success && response.data) {
          this.currentSkills = response.data
          this.editorState.isDirty = false
        }
      } catch (error) {
        console.error('Failed to load skills:', error)
      } finally {
        this.editorState.isLoading = false
      }
    },

    async saveSkills() {
      this.editorState.isLoading = true
      try {
        const response = await configApi.saveSkills(this.currentSkills)
        if (response.success) {
          this.editorState.isDirty = false
          this.editorState.lastSaved = Date.now()
          return true
        }
        return false
      } catch (error) {
        console.error('Failed to save skills:', error)
        return false
      } finally {
        this.editorState.isLoading = false
      }
    },

    addSkill(skill: SkillConfig) {
      this.currentSkills.push(skill)
      this.markDirty()
    },

    updateSkill(id: string, skill: Partial<SkillConfig>) {
      const index = this.currentSkills.findIndex(s => s.skillId === id)
      if (index !== -1) {
        this.currentSkills[index] = { ...this.currentSkills[index], ...skill }
        this.markDirty()
      }
    },

    removeSkill(id: string) {
      const index = this.currentSkills.findIndex(s => s.skillId === id)
      if (index !== -1) {
        this.currentSkills.splice(index, 1)
        this.markDirty()
      }
    },

    // === 验证管理 ===
    async validateConfigs(type?: string) {
      try {
        const response = await configApi.validateConfigs(type)
        if (response.success && response.data) {
          if (type) {
            this.validationResults[type] = response.data
          } else {
            // 全量验证
            this.validationResults = response.data
          }
        }
      } catch (error) {
        console.error('Failed to validate configs:', error)
      }
    },

    // === 搜索和过滤 ===
    updateSearchCriteria(criteria: Partial<SearchCriteria>) {
      this.searchCriteria = { ...this.searchCriteria, ...criteria }
    },

    updateSortOptions(options: Partial<SortOptions>) {
      this.sortOptions = { ...this.sortOptions, ...options }
    },

    clearSearch() {
      this.searchCriteria = {}
    },

    // === 选择管理 ===
    selectConfig(id: string) {
      this.selectedConfigs.add(id)
    },

    deselectConfig(id: string) {
      this.selectedConfigs.delete(id)
    },

    toggleSelectConfig(id: string) {
      if (this.selectedConfigs.has(id)) {
        this.selectedConfigs.delete(id)
      } else {
        this.selectedConfigs.add(id)
      }
    },

    selectAllConfigs(ids: string[]) {
      this.selectedConfigs.clear()
      ids.forEach(id => this.selectedConfigs.add(id))
    },

    clearSelection() {
      this.selectedConfigs.clear()
    },

    // === 状态管理 ===
    markDirty() {
      this.editorState.isDirty = true
    },

    markClean() {
      this.editorState.isDirty = false
      this.editorState.lastSaved = Date.now()
    },

    setServerConnection(connected: boolean) {
      this.serverConnected = connected
      if (connected) {
        this.lastSync = Date.now()
      }
    },

    // === 统计信息 ===
    async loadStats() {
      try {
        const response = await configApi.getStats()
        if (response.success && response.data) {
          this.stats = response.data
        }
      } catch (error) {
        console.error('Failed to load stats:', error)
      }
    },

    // === 自动保存 ===
    async autoSave() {
      if (!this.editorState.autoSave || !this.editorState.isDirty) {
        return
      }

      // 保存装备配置
      if (this.currentEquipments.length > 0) {
        await this.saveEquipments()
      }

      // 保存技能配置
      if (this.currentSkills.length > 0) {
        await this.saveSkills()
      }
    }
  }
})
